<template>
  <div class="common_width dm_orderDetails" v-if="show">
    <TableTitle title="支付页" v-if="orderInfo.status === 0">
      <div>
        （ 订单号： <i>{{ orderInfo.orderSn }}</i> ）
      </div>
      <div style="margin-left: 690px;">
        应付金额：
        <i style="color: red; font-size: 18px">{{ orderInfo.totalAmount }}</i>
        元
      </div>
    </TableTitle>
    <TableTitle title="订单详情" v-else>
      <div>
        （ 订单号： <i>{{ orderInfo.orderSn }}</i> ）
      </div>
      <div>订单状态： {{ status }}</div>
      <div style="margin-left: 600px;">
        金额：
        <i style="color: red; font-size: 18px">{{ orderInfo.totalAmount }}</i>
        元
      </div>
    </TableTitle>
    <el-row v-if="showPay">
      <el-col :span="12">
        <div class="box" v-if="native">
          <span class="box_message"
            >请您在
            <!-- <p>24小时</p> -->
            <CountDown
              :endTime="endTime"
              :show="show"
              v-on:changeShow="changeShow($event)"
            ></CountDown>
            内完成支付，否则订单会被自动取消</span
          >
          <div id="qrcode" ref="qrcode" class="qrcode"></div>
        </div>
        <div class="box" v-else>
          <div>
            二维码已过期，<a style="color: red" @click.prevent="freshNative"
              >刷新</a
            >页面重新获取二维码。
          </div>
          <el-image
            style="width: 298px; height: 298px; margin-top: 10px"
          ></el-image>
        </div>
      </el-col>
      <el-col :span="12"><div class="sidebar"></div></el-col>
    </el-row>
    <el-table
      :data="tableData"
      max-height="386"
      border
      style="width: 100%"
      row-key="id"
      size="small"
    >
      <el-table-column
        v-for="c in columns"
        :key="c.id"
        :prop="c.prop"
        :label="c.label"
        :width="c.width"
        align="center"
      >
        <template slot-scope="scope">
          <img
            v-if="c.prop == 'mainPicture'"
            class="imgs_style"
            :src="scope.row.productPic"
          />
          <router-link
            v-if="c.prop == 'description'"
            class="title_style"
            :to="{ name: 'detail', query: { id: scope.row.productId } }"
          >
            <span :title="scope.row.productSubTitle">{{
              scope.row.productName
            }}</span>
            <span class="ellipsis">规格：{{ scope.row.productAttr }}</span>
          </router-link>
          <span v-if="c.prop == 'price' || c.prop == 'totalprice'"
            >￥{{
              c.prop == "price"
                ? scope.row["productPrice"]
                : c.prop == "totalprice"
                ? parseFloat(scope.row["productPrice"]) *
                  scope.row["productQuantity"]
                : 0 | keepTwoDecimalPlaces
            }}</span
          >
          <span v-if="c.prop == 'num'">x{{ scope.row.productQuantity }}</span>
        </template>
      </el-table-column>
    </el-table>
    <el-row class="dm_orderDetails__pay">
      <el-col :span="12">
        <dl>
          <dt>收货人信息</dt>
          <dd>
            <i>收货人：</i>
            <span>{{ address.receiverName || "-" }}</span>
          </dd>
          <dd>
            <i>所在地区：</i>
            <span>{{
              address.receiverProvince +
                address.receiverCity +
                address.receiverRegion || "-"
            }}</span>
          </dd>
          <dd>
            <i>详情地址：</i>
            <span>{{ address.receiverDetailAddress || "-" }}</span>
          </dd>
          <dd>
            <i>联系电话：</i>
            <span>{{ address.receiverPhone || "-" }}</span>
          </dd>
        </dl>
      </el-col>
      <el-col :span="12">
        <dl>
          <dt>付款信息</dt>
          <dd>
            <i>付款时间：</i>
            <span>{{ orderInfo.createTime || "-" }}</span>
          </dd>
          <dd>
            <i>商品总数：</i>
            <span>{{ orderInfo.totalNum || "-" }} 件</span>
          </dd>
          <dd>
            <i>商品总额：</i>
            <span>￥{{ orderInfo.totalAmount || "-" }}</span>
          </dd>
          <dd>
            <i>应付金额：</i>
            <span>￥{{ orderInfo.totalAmount || "-" }}</span>
          </dd>
        </dl>
      </el-col>
    </el-row>
  </div>
  <div class="cancel" v-else>
    <div class="el-icon-error"></div>
    <span>订单已经超时被取消，请重新下单进行支付</span>
    <a href="/cart">返回我的购物车</a>
  </div>
</template>

<script>
import tableTitle from "@/components/tableTitle/index.vue";
import { getOrderDetailData } from "@/api/orderDetails";
import { formatSpecs } from "@/utils/format";
import QRCode from "qrcodejs2";
import countDown from "@/components/tools/countDown.vue";
import { getNative, getOrderStatus } from "@/api/weixinPay";
export default {
  data() {
    return {
      columns: [
        { id: 1, prop: "mainPicture", label: "图片", width: 86 },
        { id: 2, prop: "description", label: "商品" },
        { id: 3, prop: "price", label: "单价", width: 136 },
        { id: 4, prop: "num", label: "数量", width: 119 },
        { id: 5, prop: "totalprice", label: "小计", width: 136 }
      ],
      tableData: [],
      address: {},
      orderInfo: {},
      endTime: null,
      codeUrl: null,
      show: true,
      showPay: true,
      native: true,
      num: 0,
      status: null
    };
  },
  mounted() {
    try {
      const { codeUrl, orderId, orderSn } = this.$route.query || {};
      this.codeUrl = codeUrl;
      this.getOrderDetailData(orderId);
      if (typeof codeUrl !== "undefined") {
        this.qrcodeScan(codeUrl, orderSn);
      } else {
        this.showPay = false;
      }
    } catch (error) {
      console.log(error);
    }
  },
  //跳转页面的时候也应该关闭定时器
  beforeDestroy() {
    if (this.timers) {
      console.log("关闭定时器");
      clearInterval(this.timers); //关闭
    }
  },
  methods: {
    // 查询 - 订单详情
    async getOrderDetailData(orderId) {
      const res = await getOrderDetailData(orderId);
      try {
        if (res.code === 200) {
          const data = res.data || {};
          let totalNum = 0;
          data.orderItemList.forEach(item => {
            item.productAttr = formatSpecs(item.productAttr);
            totalNum = totalNum + item.productQuantity;
          });
          this.tableData = data.orderItemList;
          data.totalNum = totalNum;
          this.orderInfo = data;
          this.address = data;
          if (data.status === 0) {
            this.status = "待付款";
          } else if (data.status === 1) {
            this.status = "待发货";
          } else if (data.status === 2) {
            this.status = "已发货";
          } else if (data.status === 3) {
            this.status = "已完成";
          } else if (data.status === 4) {
            this.status = "已关闭";
          } else if (data.status === 5) {
            this.status = "无效订单";
          }
          console.log(data);
          //支付状态
          if (
            data.status === 0 &&
            data.deleteStatus === 0 &&
            typeof this.codeUrl === "string"
          ) {
            //未支付
            this.showPay = true;
            this.endTime = new Date(
              new Date(this.orderInfo.createTime).getTime() + 2 * 60 * 60 * 1000
            ).toString();
          } else if (
            data.deleteStatus === 1 ||
            data.status === 4 ||
            data.status === 5
          ) {
            //订单已取消
            this.show = false;
          }
        }
      } catch (err) {
        console.log(err);
      }
    },
    changeShow(p) {
      this.show = p;
    },
    //生成二维码，并调用监听支付状态方法
    qrcodeScan(codeUrl, orderSn) {
      let self = this;
      try {
        let qrcode = new QRCode("qrcode", {
          width: 298, // 二维码宽度
          height: 298, // 二维码高度
          text: codeUrl
        });
        self.getOrderStatus(orderSn); //生成二维码的时候调用监听支付是否成功的方法
      } catch (error) {
        this.native = false;
        console.log(error);
      }
    },
    //获取支付状态
    getOrderStatus(orderSn) {
      console.log("获取支付状态中");
      let self = this;
      this.num = 0;
      self.timers = setInterval(() => {
        //创建一个全局的定时器
        this.num++;
        console.log("次数:" + this.num);
        getOrderStatus(orderSn).then(res => {
          console.log("支付详情：");
          console.log(res);
          if (res.data && res.data.trade_state === "SUCCESS") {
            console.log("支付成功");
            //订单支付成功
            this.$router.push({
              path: "/payStatus", //成功以后的跳转路径
              query: {
                status: "success",
                payType: "2",
                totalAmount: this.orderInfo.totalAmount,
                orderId: this.orderInfo.id,
                orderSn: this.orderInfo.orderSn,
                reason: res.data.trade_state
              }
            });
            clearInterval(self.timers); //关闭定时器，否则会一直调这个接口
          } else if (res.data.trade_state === "NOTPAY") {
            //未支付
            console.log("未支付");
          } else {
            console.log("支付失败");
            this.$router.push({
              path: "/payStatus", //失败以后的跳转路径
              query: {
                status: "fail",
                reason: res.data.trade_state,
                orderId: this.orderInfo.id,
                orderSn: this.orderInfo.orderSn,
                totalAmount: this.orderInfo.totalAmount,
                payType: "2"
              }
            });
            clearInterval(self.timers); //关闭定时器，否则会一直调这个接口
          }
        });
        if (this.num >= 5) {
          //这里是判断this.num++到500的情况下用户还没有支付则自动关闭定时器和二维码
          console.log("二维码超时");
          this.native = false;
          if (this.num == 10) {
            clearInterval(self.timers);
            this.num = 0;
            this.$router.push({
              path: "/payStatus", //失败以后的跳转路径
              query: {
                status: "fail",
                reason: "NOTPAY",
                orderId: this.orderInfo.id,
                orderSn: this.orderInfo.orderSn,
                totalAmount: this.orderInfo.totalAmount,
                payType: "2"
              }
            });
            console.log("关闭计时器");
            clearInterval(self.timers);
          }
        }
      }, 5000);
    },
    //刷新二维码
    freshNative() {
      let self = this;
      console.log("二维码刷新");
      clearInterval(self.timers);
      this.num = 0;
      this.native = true;
      const data = {
        outtradeno: this.orderInfo.orderSn,
        totalfee: this.orderInfo.totalAmount,
        orderId: this.orderInfo.id,
        payType: "2"
      };
      if (data) {
        getNative(data).then(res => {
          if (res.code === 200) {
            this.codeUrl = res.data.code_url;
            this.qrcodeScan(this.codeUrl, this.orderInfo.orderSn);
          }
        });
      }
    }
  }
};
</script>

<style lang="scss">
@import "@/assets/css/orderDetails/index.scss";
</style>
